/*******************************************************************************
 * Copyright (c) 2002 Boris Pruessmann and others.
 * All rights reserved.   This program and the accompanying materials
 * are made available under the terms of the Common Public License v0.5
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/cpl-v05.html
 * 
 * Contributors:
 *    Boris Pruessmann - Initial implementation.
 ******************************************************************************/
package net.sourceforge.perforce.ui.action;

import java.util.HashSet;
import java.util.Set;

import net.sourceforge.perforce.core.PerforceCorePlugin;
import net.sourceforge.perforce.core.PerforceException;
import net.sourceforge.perforce.core.api.IPerforceServer;
import net.sourceforge.perforce.core.resources.IP4File;
import org.eclipse.jface.action.IAction;

/**
  * @version $Revision: 202 $
  * @author  <a href="mailto:bpruessmann@users.sourceforge.net">Boris Pruessmann</a>
  */
public class ScheduleForResolveAction extends P4FileAction
{
	// ------------------------------------------------------------------------------ Public Methods

	/** @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction) */
	public void run(IAction action) 
	{
		IP4File[] files = getSelectedPerforceFiles();
		
		Set serverSet = new HashSet(); 
		try
		{
			for (int i = 0; i < files.length; i++)
			{
				IP4File file = files[i];
				
				IPerforceServer server = file.getServer();
				server.sync(file.getLocation().toOSString(), "#head", null);
				serverSet.add(server);
			}
		}
		catch (PerforceException e)
		{
			handle(e);
		}
		finally
		{
			if (!serverSet.isEmpty())
			{
				IPerforceServer[] servers = 
					(IPerforceServer[]) serverSet.toArray(new IPerforceServer[serverSet.size()]);
				PerforceCorePlugin.getPlugin().broadcastChangelistStateChanges(servers);
			}
		}
	}
	
	// --------------------------------------------------------------------------- Protected Methods

	/** @see net.sourceforge.perforce.ui.action.PerforceAction#isEnabled() */
	protected boolean isEnabled() 
	{
		IP4File[] files = getSelectedPerforceFiles();
		for (int i = 0; i < files.length; i++)
		{
			IP4File file = files[i];
			
			if (!file.getClientName().equals(file.getServer().getClient()))
			{
				return false;
			}
		}
		return true;
	}	
}
